package com.app.mingluxing.location;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.alibaba.fastjson.JSONObject;
import com.app.mingluxing.R;
import com.app.mingluxing.adapter.SimpleAdapter;
import com.app.mingluxing.base.BaseActivity;
import com.app.mingluxing.bean.LocationList;
import com.app.mingluxing.bean.LocationsResBean;
import com.app.mingluxing.net.HttpUtil;
import com.app.mingluxing.utils.AbDateUtil;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.Constant;
import com.app.mingluxing.utils.DensityUtil;
import com.app.mingluxing.utils.LogUtil;
import com.app.mingluxing.widget.BatteryView;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;

import java.util.Date;
import java.util.List;


/**
 * 历史轨迹
 * Created by Aaron on 15/8/4.
 */
public class HistoryActivity extends BaseActivity {

    private MapView mMapView;
    private BaiduMap mBaiduMap;
//    private double myLatitude;
//    private double myLongitude;

    private MyLocationConfiguration.LocationMode mCurrentMode;
    private MyLocationListenner myListener = new MyLocationListenner();
    // 定位相关
    private LocationClient mLocClient;
    //是否是第一次定位
    private boolean isFirstLoc = true;
    private long firstTimeOfDay = AbDateUtil.getFirstTimeOfDay();
    private TextView tv_right;
    private TextView tv_title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_history);
        overridePendingTransition(R.anim.translate_in, R.anim.translate_out);

        // 构建Marker图标
        mBitmap = BitmapDescriptorFactory.fromResource(R.drawable.thumb);

        initWidget();

        //默认获取0点到当前时间的历史轨迹
        getHistoryRecord(firstTimeOfDay, new Date().getTime());

    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
//        iv_left.setImageResource(R.drawable.arrow_down);

        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(getResources().getString(R.string.today));
        tv_right = (TextView) findViewById(R.id.tv_right);
        tv_right.setText(getResources().getString(R.string.time_select));

        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bMapView);

        // 获取地图控件引用
        mBaiduMap = mMapView.getMap();

        //地图缩放比例
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(16.0f);
        mBaiduMap.setMapStatus(msu);

        //点击地图其它部位 隐藏window
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {

            @Override
            public boolean onMapPoiClick(MapPoi arg0) {
                return false;
            }

            @Override
            public void onMapClick(LatLng arg0) {
                if (mBaiduMap != null)
                    mBaiduMap.hideInfoWindow();
            }
        });

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker arg0) {

                showBabyLocationInfo(arg0);
                LogUtil.e("tag", "======  OnMarkerClick  ======");
                return false;
            }

        });

        //隐藏缩放按钮
        View zoom = null;

        for (int i = 0; i < mMapView.getChildCount(); i++) {

            View child = mMapView.getChildAt(i);

            if (child instanceof ZoomControls) {
                zoom = child;
                break;
            }

        }

        zoom.setVisibility(View.INVISIBLE);

        //获取我的位置
        getMyLocation();

        iv_left.setOnClickListener(this);
        tv_title.setOnClickListener(this);
        tv_right.setOnClickListener(this);

    }

    private TextView tv_barry;
    private TextView tv_time;
    private BatteryView iv_barry;
    private TextView adrress;

    //
    private void showBabyLocationInfo(Marker marker) {

        if (marker == null) {
            adrress.setText("");
            tv_barry.setText("");
            tv_time.setText("");
            return;
        }

        LayoutInflater inflater = getLayoutInflater();

        View view = inflater.inflate(R.layout.alog_showbaby_location, null);
        view.setPadding(5, 5, 5, 5);
//        view.setBackgroundResource(R.drawable.ic_mylocation_bg);

        tv_barry = (TextView) view.findViewById(R.id.tv_barry);
        tv_time = (TextView) view.findViewById(R.id.tv_time);
        iv_barry = (BatteryView) view.findViewById(R.id.iv_barry);
        adrress = (TextView) view.findViewById(R.id.adrress);

        InfoWindow myInfoWindow = new InfoWindow(view, marker.getPosition(), 10);
        mBaiduMap.showInfoWindow(myInfoWindow);

        LocationList info = (LocationList) marker.getExtraInfo().get("info");

        if (info == null)
            return;

        tv_time.setText(AbDateUtil.getStringByFormat(info.updateTime, "yyyy-MM-dd HH:mm:ss"));
        adrress.setText(info.addressDescription);
        tv_barry.setText(info.battery + "%");

        if (!CommonUtils.isNull(info.battery)) {

            tv_barry.setText(info.battery + "%");
            int currentBattery = Integer.parseInt(info.battery);

            if (currentBattery <= 20) {//电量小于20变红

                iv_barry.setLength(35, 15, 5, 10, 1);
                iv_barry.setColor(Color.BLACK, Color.RED);

            } else { //大于20是绿的

                iv_barry.setLength(35, 15, 5, 10, 1);
                iv_barry.setColor(Color.BLACK, Color.GREEN);
            }

            if (currentBattery <= 5) {
                iv_barry.setPower(5);
            } else {
                iv_barry.setPower(currentBattery);
            }

        }
    }

    /**
     * 获取历史轨迹信息
     */
    private void getHistoryRecord(long starTime, long endTime) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("id", sp.getString(Constant.CURRENTCHILDID, ""));
        j.put("startTime", starTime);
        j.put("endTime", endTime);

        HttpUtil.setPostRequest("获取中...", this, Constant.WEB_ROOT + Constant.GETCHILDLOCLIST,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            LocationsResBean locationsResBean = JSONObject.parseObject(str, LocationsResBean.class);

                            if (Constant.STATUS_SUCCESS == locationsResBean.code) {

                                List<LocationList> locationList = locationsResBean.locationList;

                                if (locationList == null || locationList.size() == 0) {
                                    showToast("未查询到该时间段的定位信息");

                                    if (mBaiduMap != null)
                                        mBaiduMap.clear();

                                    return;
                                }

                                //创建历史定位图标
                                createLocationMarks(locationList);

                            } else {
                                showToast(Constant.showErrorMsg(locationsResBean.code, HistoryActivity.this));
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, null);

    }

    private BitmapDescriptor mBitmap;

    /**
     * 创建历史定位图标
     *
     * @param locationList
     */
    private void createLocationMarks(List<LocationList> locationList) {
        if (mBaiduMap != null)
            mBaiduMap.clear();
        //根据服务器返回的点的集合个数,创建多少个点
        for (int i = 0; i < locationList.size(); i++) {

            //创建点
            LatLng point = new LatLng(locationList.get(i).baiduLat, locationList.get(i).baiduLon);
            MarkerOptions option = new MarkerOptions().position(point).icon(mBitmap).zIndex(5);
            Marker marker = (Marker) (mBaiduMap.addOverlay(option));

            Bundle bundle = new Bundle();
            bundle.putSerializable("info", locationList.get(i));
            marker.setExtraInfo(bundle);

            // 定位到该点
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(point);
            mBaiduMap.setMapStatus(u);

        }

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left:
                finish();
                break;

            case R.id.tv_right:

                selectTimeQuantum(v);

                break;

            case R.id.tv_title:

                Intent intent = new Intent(this, ChooseDateActivity.class);
                startActivityForResult(intent, 24);

                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case 24:

                if (data == null)
                    return;

                //选择的日期
                firstTimeOfDay = data.getLongExtra("date", 0);

                tv_title.setText(AbDateUtil.getStringByFormat(firstTimeOfDay, AbDateUtil.dateFormatYMD));

                selectTimeQuantum(tv_right);

                break;

        }

    }

    /**
     * 选择时间段
     */
    @Deprecated
    private void selectTimeQuantum(View v) {

        View popuView = View.inflate(this, R.layout.popup_choose_time_quantum, null);

        final PopupWindow areaPup = new PopupWindow(popuView,
                DensityUtil.dip2px(this, 120), DensityUtil.dip2px(this, 300));
//        areaPup.setContentView(popuView);
        areaPup.setOutsideTouchable(true);

        areaPup.setFocusable(true);
        areaPup.setBackgroundDrawable(new BitmapDrawable());
        //x y
        areaPup.showAsDropDown(v, 0, 0);

        ListView lv_time = (ListView) popuView.findViewById(R.id.lv_time);

        SimpleAdapter adapter = new SimpleAdapter(this, getResources().getStringArray(R.array.tims_quantum));

        lv_time.setAdapter(adapter);

        lv_time.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (areaPup != null && areaPup.isShowing())
                    areaPup.dismiss();

                //获取到选择的开始时间和结束时间
                long firstTime = firstTimeOfDay + (2 * 60 * 60 * 1000) * i;

                long lastTime = firstTime + (2 * 60 * 60 * 1000);

                getHistoryRecord(firstTime, lastTime);

            }
        });

    }

    /**
     * 获取到我的当前位置
     */
    private void getMyLocation() {
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_center_point_my);
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
//       //定位的点击事件
//        mBaiduMap.setOnMyLocationClickListener(new OnMyLocationClickListener() {
//
//            @Override
//            public boolean onMyLocationClick() {
//
//                LatLng latLng = new LatLng(myLatitude, myLongitude);
//                showMyLocationInfo(latLng);
//                return false;
//            }
//        });

        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(100000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }


    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null)
                return;
            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();

//            LogUtil.e("tag", "我的坐标点" + location.getLatitude() + "," + location.getLongitude());

//            mApplication.myLatitude = location.getLatitude();
//            mApplication.myLongitude = location.getLongitude();

            mBaiduMap.setMyLocationData(locData);


//            if (isFirstLoc) {
//                isFirstLoc = false;
////                //如果未绑定设备则定位到我的位置,否则定位到手表的位置
////                if (TextUtils.isEmpty(currentWatchId)) {
//
//                try {
//                    LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
//                    MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
//                    if (mBaiduMap != null)
//                        mBaiduMap.animateMapStatus(u);
//                } catch (Exception e) {
//                    e.printStackTrace();
//
//                }
//
////                }
//            }

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMapView != null)
            mMapView.onDestroy();

        mApplication.cancelPendingRequests(getClass().getName());
    }

    @Override
    public void onResume() {
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        if (mMapView != null)
            mMapView.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (mMapView != null)
            mMapView.onPause();
    }

    @Override
    public void finish() {
        super.finish();

        overridePendingTransition(R.anim.translate_in, R.anim.translate_out);
    }
}
